<template>
  <el-dialog :close-on-click-modal="false" append-to-body :title="title" :visible.sync="visible" width="1000px">
    <div class="add-form">
      <el-form ref="form" :model="form" label-width="120px" :rules="rules" :disabled="type === 'view'">
        <el-form-item label="后台单号" prop="xmbzNo">
          <el-input class="w-200 mr-10" v-model.trim="form.xmbzNo" size="small" placeholder="后台单号" clearable :disabled="type == 'edit'"></el-input>
          <el-button type="primary" size="small" @click="handleSearch" plain icon="el-icon-search">搜索</el-button>
        </el-form-item>
        <el-form-item label="生产备注">
          <el-input class="" v-model.trim="form.productionNotes" size="small" placeholder="生产备注" clearable></el-input>
        </el-form-item>
        <el-form-item label="配送备注">
          <el-input class="" v-model.trim="form.deliveryNotes" size="small" placeholder="配送备注" clearable></el-input>
        </el-form-item>
        <el-form-item label="配送时间" prop="deliveryDate">
          <div class="d-f">
            <el-date-picker
              type="date"
              size="medium"
              v-model="deliveryDate"
              :picker-options="pickerOptionsStart"
              :clearable="false"
              placeholder="配送日期"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              class="w-180 mr-10"
              :disabled="true"
            ></el-date-picker>
            <div> - </div>
            <selecttime
              ref="selecttime"
              :deliveryTime="deliveryDate"
              OrderStartTime=""
              OrderEndTime=""
            ></selecttime>
          </div>
        </el-form-item>
        <el-form-item label="仓库" prop="deptId">
          <CitySelect ref="CitySelect" class="mr-10 w-100" size="small" v-model="form.deptId" placeholder="城市" @change="handleCityChange"></CitySelect>
          <XmSelect ref="mainWarehouse" class="mr-10" size="small" v-model="form.mainWarehouseId" :options="mainWarehouseList" :config="{
            labelKey: 'deptName',
            valueKey: 'id'
          }" placeholder="总仓" @visible-change="getMainWarehouseListByCity" @change="form.warehouseId = ''"></XmSelect>
          <XmSelect ref="warehouse" class="mr-10" size="small" v-model="form.warehouseId" :options="branchWarehouseList" :config="{
            labelKey: 'name',
            valueKey: 'id'
          }" placeholder="仓库" @visible-change="getBranchWarehouseList"></XmSelect>
        </el-form-item>
        <el-form-item label="修改原因" prop="reason" v-if="showReason">
          <div class="d-f ai-c">
            <XmSelect ref="reason" class="mr-10" size="small" v-model="form.reason" :options="reasonList" placeholder="修改原因"></XmSelect>
            <el-tooltip content="修改了时间或地址，请选择原因" placement="top-start">
              <i class="el-icon-info fz-24 mr-10"></i>
            </el-tooltip>
          </div>
          <div class="c-999">原配送时间：{{ originTime }}</div>
          <div class="c-999">原配送地址：{{ originAddress }}</div>
        </el-form-item>
        <el-form-item label="定位">
          <AddressSearch size="small" v-model.trim="locationAddress" @selectAddress="handleSelectAddress" :deptName="deptName"></AddressSearch>
        </el-form-item>
        <el-form-item label="地址" prop="receiverAddress">
          <el-input class="" v-model.trim="form.receiverAddress" size="small" placeholder="生产备注" clearable></el-input>
        </el-form-item>
        <div class="map-box">
          <XmMap ref="xmMap"></XmMap>
        </div>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submit" v-show="type !== 'view'" :loading="loading">{{ loading ? '提交中...' :
          '提交'
      }}</el-button>
    </span>

  </el-dialog>
</template>

<script>
import { saveOrderModify } from '@/api/workorder/modifyOrder';
import {
  orderList, // 查询
} from "@/api/pending";
import {
  getMainWarehouseList, // 获取分仓
  getSeparateWarehouseList, // 获取分仓
  getWarehouseName, // 根据经度纬度，返回分仓总仓名称
} from "@/api/createOrder";
import selecttime from "@/components/foundorder/selecttime"; // 配送时间组件
import { getWarehouseLabel } from '@/util/map'
import { getWarehouseList, getWarehouseByType } from "@/api/warehouse";

const reasonList = [{
  label: '卡点已沟通延迟',
  value: '卡点已沟通延迟'
},{
  label: '真实号码收不到短信',
  value: '真实号码收不到短信'
},{
  label: '真实号码回复失败',
  value: '真实号码回复失败'
},{
  label: '联系不上已沟通延迟',
  value: '联系不上已沟通延迟'
},{
  label: '虚拟号修改时间',
  value: '虚拟号修改时间'
},{
  label: '客户修改地址',
  value: '客户修改地址'
},{
  label: '定位错误',
  value: '定位错误'
}]

const extJsonKeys = ['deliveryNotes', 'productionNotes', 'receiverAddress', 'longitude', 'latitude', 'deliveryStartTime', 'deliveryEndTime', 'deptId', 'deptName', 'mainWarehouseId', 'mainWarehouse', 'warehouseId', 'branchWarehouse'];

export default {
  components: {
    selecttime
  },
  data() {
    const validateDeliveryTime = (rule, value, callback) => {
      const timeRef = this.$refs.selecttime
      if (!this.deliveryDate) {
        return callback(new Error("请选择配送日期！"));
      } else if (!timeRef.getStartTime() || !timeRef.getEndTime()) {
        return callback(new Error("请选择配送时间！"));
      }
      callback()
    }

    const validateWarehouse = (rule, value, callback) => {
      if (!this.form.deptId) {
        return callback(new Error("请选择城市！"));
      } else if (!this.form.mainWarehouseId) {
        return callback(new Error("请选择总仓！"));
      } else if (!this.form.mainWarehouseId) {
        return callback(new Error("请选择仓库！"));
      }
      callback()
    }
    return {
      reasonList,
      visible: false,
      loading: false,
      type: "add",
      form: {
        "xmbzNo": "",
        "platformOrderId": "",
        "deptId": "",
        "reason": "",
      },
      rules: {
        xmbzNo: [{required: true,message: '请填写后台单号',trigger: 'blur'}],
        deliveryDate: [{required: true,validator: validateDeliveryTime,trigger: 'blur'}],
        deptId: [{required: true,validator: validateWarehouse,trigger: 'change'}],
        receiverAddress: [{required: true,message: '请填写地址',trigger: 'blur'}],
        reason: [{required: true,message: '请选择原因',trigger: 'change'}],
      },
      deliveryDate: '',
      orderData: {},
        // 日期
      pickerOptionsStart: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      mainWarehouseList: [],
      branchWarehouseList: [],
      locationAddress: '',
      deptName: '',
      originTime: '',
      originAddress: '',
    }
  },
  methods: {
    show({ type, data, orderData }) {
      this.clearForm()
      this.type = type
      this.orderData = orderData || {}
      this.visible = true
      if (orderData) {
        this.form.xmbzNo = orderData.xmbzNo
        this.form.platformOrderId = orderData.platformOrderId
      }
      if (data) {
        this.form = {
          ...data,
        }
        try {
          this.form.pics = JSON.parse(data.extJson).img.map(item => {
            return {
              url: item
            }
          })
        } catch (error) {
          console.error(error)
          this.form.pics = []
        }
      }
      
    },
    clearForm() {
      this.form = {
        "xmbzNo": "",
        "deptId": "",
        "locationAddress": "",
        "reason": "",
      }
      this.$refs.selecttime && this.$refs.selecttime.setTime('', '')
      this.$refs.form && this.$refs.form.clearValidate()
      this.originTime = ''
      this.originAddress = ''
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          saveOrderModify(this.getParams()).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: `提交成功！`
              })
              this.visible = false
              this.$emit('submit')
            } else {
              this.$message({
                type: 'error',
                message: res.data.msg
              })
            }
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    getParams() {
      const extJson = {};
      extJsonKeys.forEach(key => {
        if (key === 'deliveryStartTime') {
          const startTime = this.deliveryDate + ' ' + this.$refs.selecttime.getStartTime()
          if (startTime !== this.originOrderData['deliveryStartTime']) {
            extJson['deliveryStartTime'] = startTime
          }
        } else if (key === 'deliveryEndTime') {
          const endTime = this.deliveryDate + ' ' + this.$refs.selecttime.getEndTime()
          if (endTime !== this.originOrderData['deliveryEndTime']) {
            extJson['deliveryEndTime'] = endTime
          }
        } else if (key === 'deptId') {
          const deptName = this.$refs.CitySelect.getSelectedLabel();
          if (this.form['deptId'] != this.originOrderData['deptId']) {
            extJson['deptId'] = this.form['deptId'];
            extJson['deptName'] = deptName;
          }
        } else if (key === 'mainWarehouseId') {
          const mainWarehouse = this.$refs.mainWarehouse.getSelectedLabel();
          if (this.form['mainWarehouseId'] != this.originOrderData['mainWarehouseId']) {
            extJson['mainWarehouseId'] = this.form['mainWarehouseId'];
            extJson['mainWarehouse'] = mainWarehouse;
          }
        } else if (key === 'warehouseId') {
          const branchWarehouse = this.$refs.warehouse.getSelectedLabel();
          if (this.form['warehouseId'] != this.originOrderData['warehouseId']) {
            extJson['warehouseId'] = this.form['warehouseId'];
            extJson['branchWarehouse'] = branchWarehouse;
          }
        } else if (this.form[key] != this.originOrderData[key]) {
          extJson[key] = this.form[key];
        }
      })
      const params = {
        id: this.type === 'add' ? undefined : this.orderData.id,
        orderId: this.form.id,
        xmbzNo: this.form.xmbzNo,
        platformOrderId: this.form.platformOrderId,
        cityId: this.form.deptId,
        cityName: this.$refs.CitySelect.getSelectedLabel(),
        reason: this.showReason ? this.form.reason : undefined,
        "extJson": JSON.stringify(extJson),
      }
      return params
    },
    //  添加投诉图片列表
    addabnormalSuccess (response) {
      this.form.pics.push({
        url: response.data
      })
    },
    //  删除投诉图片列表
    addabnormalRemove (data) {
      this.form.pics.map((item, index) => {
        if (item.uid == data.uid) {
          this.form.pics.splice(index, 1)
        }
      })
    },
    handleSearch() {
      if (!this.form.xmbzNo) {
        this.$message({
          type: 'info',
          message: '请填写后台单号'
        })
        return
      }
      orderList({
        xmbzNo: this.form.xmbzNo,
        orderTimeSort: 0, // 下单时间排序
        deliveryTimeSort: 0, // 配送时间排序
      }).then(res => {
        if (res.data.data && res.data.data.rows.length) {
          this.form = res.data.data && res.data.data.rows && res.data.data.rows[0];
          this.originOrderData = {
            ...this.form
          }
          this.locationAddress = this.originAddress = this.form.receiverAddress;
          this.deliveryDate = this.form.deliveryStartTime && this.form.deliveryStartTime.slice(0, 10);
          this.originTime = `${this.form.deliveryStartTime.slice(11, 16)} - ${this.form.deliveryEndTime.slice(11, 16)}`;
          this.getMainWarehouseListByCity();
          this.getBranchWarehouseList();
          this.clearMap()
          this.addMarkder(this.form.longitude, this.form.latitude, this.locationAddress)
          this.addWarehouseOnMap();
          this.addPlatformWarehouseOnMap();

          this.$nextTick(() => {
            this.$refs.selecttime && this.$refs.selecttime.setTime(
              this.form.deliveryStartTime.slice(11, 16),
              this.form.deliveryEndTime.slice(11, 16),
            )
          })
        } else {
          this.$message({
            type: 'error',
            message: '查询不到该单号记录！'
          })
        }
      })
    },
    // 根据经纬度加载仓库信息
    loadWarehouseByLocation(location) {
      getWarehouseName(location).then(res => {
        if (res.data.data && res.data.data.deptId) {
          const warehose = res.data.data;
          this.form.deptId = warehose.cityId;
          this.form.mainWarehouseId = warehose.deptId;
          this.form.warehouseId = warehose.id + '';

          this.getMainWarehouseListByCity();
          this.getBranchWarehouseList();
          this.addWarehouseOnMap();
          this.addPlatformWarehouseOnMap();
        } else {
          this.$confirm(
              "您选择的地址不在配送范围内！",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
        }
      })
    },
    handleCityChange() {
      this.form.mainWarehouseId = '';
      this.form.warehouseId = '';
      this.clearWarehouseMarkers();
      this.addWarehouseOnMap();
      this.addPlatformWarehouseOnMap();
    },
    getMainWarehouseListByCity() {
      if (!this.form.deptId) {
        this.$message({
          type: 'error',
          message: '先选择城市'
        })
        return
      }
      getMainWarehouseList({parentId: this.form.deptId}).then(res => {
        this.mainWarehouseList = res.data.data || []
      })
    },
    getBranchWarehouseList() {
      if (!this.form.mainWarehouseId) {
        this.$message({
          type: 'error',
          message: '请先选择总仓'
        })
        return
      }
      getSeparateWarehouseList({deptId: this.form.mainWarehouseId}).then(res => {
        this.branchWarehouseList = (res.data.data || []).map(item => {
          return {
            ...item,
            id: item.id + ''
          }
        })
      })
    },
    handleSelectAddress(address) {
      this.locationAddress = address.name
      this.form.longitude = address.lng
      this.form.latitude = address.lat
      this.clearMap()
      this.addMarkder(address.lng, address.lat, `<div class='info'>${address.name}</div>`)

      this.loadWarehouseByLocation({
        longitude: address.lng,
        latitude: address.lat,
      })
    },
    addMarkder(lng, lat, content) {
      this.marker = this.$refs.xmMap.createMarker({
        longitude: lng,
        latitude: lat,
        label: {
          content: content
        },
        icon: {
          image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png'
        },
        zIndex: 50
      })
      this.$refs.xmMap.map.add([this.marker])
      this.$refs.xmMap.setZoomAndCenter(13, [lng, lat])
    },
    clearMap() {
      this.$refs.xmMap.clearMap()
    },
    // 添加仓库区域
    addWarehouseOnMap() {
      getWarehouseList({ cityId: this.form.deptId }).then(res => {
        const resData = res.data.data || [];
        if (resData && resData.length) {
          const markers = resData.map(item => {
            return this.$refs.xmMap.createMarker({
              longitude: item.longitude,
              latitude: item.latitude,
              label: {
                content: getWarehouseLabel(item)
              },
            })
          });

          const polygonPath = resData.map(item => {
            return item.geoJson.geometry.coordinates[0]
          })
          const polygon = this.$refs.xmMap.createPolygon({
            path: polygonPath,
            strokeColor: "#000",
            strokeWeight: 3,
            strokeOpacity: 1,
            fillOpacity: 0.4,
            fillColor: "#fff",
            zIndex: 40,
          });
          this.$refs.xmMap.map.add([...markers, polygon])
          this.warehoseMarkers = this.warehoseMarkers.concat([...markers, polygon])
        }
      })
    },
    // 添加平台仓区域
    addPlatformWarehouseOnMap() {
      getWarehouseByType({
        cityId: this.form.deptId,
        type: 99,// 平台仓
      }).then(res => {
        const resData = res.data.data || []
        if (resData && resData.length) {
          const markers = resData.map(item => {
            return this.$refs.xmMap.createMarker({
              longitude: item.longitude,
              latitude: item.latitude,
              label: {
                content: getWarehouseLabel(item)
              },
            })
          });

          const polygonPath = resData.map(item => {
            return item.geoJson.geometry.coordinates[0]
          })
          const polygon = this.$refs.xmMap.createPolygon({
            path: polygonPath,
            strokeColor: "#FF33FF",
            strokeWeight: 2,
            strokeOpacity: 1,
            fillOpacity: 0.4,
            fillColor: "#1791fc",
            zIndex: 50,
          });
          this.$refs.xmMap.map.add([...markers, polygon])
          this.warehoseMarkers = this.warehoseMarkers.concat([...markers, polygon])
        }
      })
    },
    // 清除仓库坐标
    clearWarehouseMarkers() {
      if (this.warehoseMarkers.length > 0) {
        this.$refs.xmMap.map.remove(this.warehoseMarkers)
        this.warehoseMarkers = []
      } 
    }
  },
  watch: {
    'form.deptId'(newVal) {
      this.$nextTick(() => {
        this.deptName = this.$refs.CitySelect && this.$refs.CitySelect.getSelectedLabel();
      })
    }
  },
  computed: {
    title() {
      const textMap = {
        'add': '新 增',
        'edit': '编 辑',
        'view': '查 看',
      }
      return textMap[this.type]
    },
    showReason() {
      const currentTime = (this.$refs.selecttime && this.$refs.selecttime.getStartTime()) ? `${this.$refs.selecttime.getStartTime().slice(0, 5)} - ${this.$refs.selecttime.getEndTime().slice(0, 5)}` : ''
      if (currentTime && this.originTime && this.originTime != currentTime) {
        return true
      }
      if (this.originAddress && this.originAddress != this.form.receiverAddress) {
        return true
      }
      return false
    },
  },
  created() {
    this.warehoseMarkers = []
  },
}
</script>

<style lang="scss" scoped>
.add-form {}
.map-box {
  border: 1px solid #ddd;
  margin-top: 10px;
}
</style>
